// 对user操作的model
import React from 'react';
import {Model, Effect} from 'dva-core-ts';
import {Reducer} from 'redux';
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Toast from 'react-native-root-toast';
export interface IWorks {
  work_id: string;
  work_url: string;
}
export interface IPublish {}
export interface ILike {}
export interface IGoods {}
export interface IAddress {
  address_id: string;
  Consigner_name: string; // 收货名称
  consigner_phone: number;
  address_message: string;
  isDefaultAddress: boolean;
}
export interface IUserInfo {
  works?: IWorks[];
  publish?: IPublish[];
  Like?: ILike[];
  Goods?: IGoods[];
  Address?: IAddress[];
  _id?: string;
  username?: string;
  password?: string;
  identity?: string;
  experience?: number;
  city?: string;
  nature?: string; // 性格
  scurpture?: string; // 头像
  age?: number;
}
export interface UserInfoModelState {
  userInfo?: IUserInfo[];
  photographerInfoByName?:IUserInfo[];
  user:IUserInfo[]
}
const USER_URL = '/users/list';
const PHOTOGRAPHER_URL = '/Photographer/list';
const LOGIN_URL = '/login';
const REGISTER_URL = '/register';
const MODIFYPASSWROD_URL = '/modifyPassword';
const ADDADDRESS_URL = "/addAddress";
const DELETE_URL = "/deleteAddress";
const MODIFYADDRESS_URL = "/modifyAddress";
const APPLYADDRESS_URL = "/applyAddress";
const CURREBTUSER_URL = "/currentUser";
const COMPELETEINFO_URL = "/compeleteInfo";
const EDITUSERINFO_URL = "/editUserInfo";
const LIKEARTICAL_URL = "/likeArtical";
const CANCELLIKEARTICAL_URL = '/cancelLikeArtical';
const DESTROYACCOUNT_URL = '/destroyAccount';

interface UserModel extends Model {
  namespace: 'users';
  state?: UserInfoModelState;
  reducers?: {
    updateState: Reducer<IUserInfo>;
  };
  effects?: {
    getUserInfo: Effect;
    getPhotographerInfoByName: Effect;
    register:Effect;
    login:Effect;
    modifyPassword:Effect;
    addAddress:Effect;
    // 获取当前用户，因为直接将用户使用AsyncStorage保存在本地在更新用户中的某些数据的时候不能够及时更新AsyncStorage
    // AsyncStorage只在登录成功时保存一次，鉴于此，应该有一个可以实时获取当前用户信息的接口
    getCurrentUser:Effect;
    // 清空当前用户，在退出登录的时候，不仅需要把Async里面的token和currentUserInfo清空，还需要把当前保存的user清空
    clearCurrentUser:Effect;
    deleteAddress:Effect;
    modifyAddress:Effect;
    // 应用收货地址，也就是吧当前地址设置成默认地址，默认地址就是Address数组中的第一个，所以只需要把当前Apply的地址放到Address中第一位
    applyAddress:Effect;
    // 成为摄影师页面完善摄影师身份接口
    compeleteInfo:Effect;
    // 编辑详细信息
    editUserInfo:Effect;
    // 收藏文章
    likeArticals:Effect;
    // 取消收藏文章
    cancelLikeArtical:Effect;
    // 注销账号
    destroyAccount:Effect;
  };
}
const initValue = {
  userInfo: [],
  photographerInfoByName:[],
  user:[]
};
const users: UserModel = {
  namespace: 'users',
  state: initValue,
  reducers: {
    updateState: (state, {payload}) => {
      return {
        ...state,
        ...payload,
      };
    },
  },
  effects: {
    // dispatch触发时会传递payload
    // 请求整个user列表
    *getUserInfo({callback}, {call, put, select}): any {
      const res = yield call(axios.get, USER_URL);
      if (res.data.code === 200) {
        yield put({
          type: 'updateState',
          payload: {
            userInfo: res.data.data,
          },
        });
        // const { users } = yield select(state => state);
        if (typeof callback === 'function') {
          callback(res.data.data);
        }
      }
    },
    *getPhotographerInfoByName({payload},{call,put}):any {
      console.log('photographer_name',payload.photographer_name)
      const res = yield call(axios.get, PHOTOGRAPHER_URL,{
        params:{photographer_name:payload.photographer_name}
      });
      console.log('res.data.data',res.data.data)
      if(res.data.code === 200 ){
        yield put({
          type:"updateState",
          payload:{
            photographerInfoByName:res.data.data
          }
        })
      }
      if(payload.callback && typeof payload.callback === "function") {
        payload.callback(res.data.data)
      }
    },
    *register({payload},{call,put}):any {
      console.log('注册的数据',payload.formData);
      // 处理formData数据
      const formData = new FormData();
      formData.append('username', payload.formData.username);
      formData.append('password', payload.formData.password);
      formData.append('age', payload.formData.age);
      formData.append('city', payload.formData.city);
      formData.append('nature', payload.formData.nature);
      formData.append('identity', payload.formData.identity);
      formData.append('scurpture', {
        uri: payload.formData.scurpture,
        name: 'scurpture.jpg',
        type: 'image/jpeg',
      });
      console.log("转化成formData之后的数据",formData)
      const res = yield call(axios.post, REGISTER_URL,formData,{
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      console.log('注册接口返回的数据',res.data.data)
      if(res.data.code === 200 ){
        if(payload.callback && typeof payload.callback === "function") {
          payload.callback(res.data.data)
        }
      }else {
        Toast.show(res.data.message, {
          position: Toast.positions.CENTER,
          duration: Toast.durations.LONG,
          shadow: true,
          animation: true,
        });
      }
    },
    *login({payload},{call,put}):any {
      console.log('登录的数据',payload.formData);
      // 处理formData数据
      const formData = new FormData();
      formData.append('username', payload.formData.username);
      formData.append('password', payload.formData.password);
      console.log("登录转化成formData之后的数据",formData)
      const res = yield call(axios.post, LOGIN_URL,formData,{
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      console.log('登录接口返回的数据',res.data);
      if(res.data.code === 200 ){
        // 把token保存在本地
        AsyncStorage.setItem('token', res.data.data.token);
        // 把当前用户的信息保存起来
        // 不保存在dva是因为dva一刷新就没了，而token还在，两者就不同步了
        AsyncStorage.setItem('currentUserInfo', JSON.stringify(res.data.data.loginUserInfo));
        if(payload.callback && typeof payload.callback === "function") {
          // 把当前用户的信息和token信息都返回
          payload.callback(res.data.data)
        }
      } else {
        Toast.show(res.data.message, {
          position: Toast.positions.CENTER,
          duration: Toast.durations.LONG,
          shadow: true,
          animation: true,
        });
      }
      
    },
    *modifyPassword({payload},{call,put}):any {
      console.log('修改密码的数据',payload.formData);
      // 处理formData数据
      const formData = new FormData();
      formData.append('user_id', payload.formData.user_id);
      formData.append('newPassword', payload.formData.newPassword);
      console.log("修改密码转化成formData之后的数据",formData)
      const res = yield call(axios.post, MODIFYPASSWROD_URL,formData,{
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      console.log('修改密码接口返回的数据',res);
      if(res.data.code === 200 ){
        if(payload.callback && typeof payload.callback === "function") {
          payload.callback()
        }
      } else {
        Toast.show('修改密码失败', {
          position: Toast.positions.CENTER,
          duration: Toast.durations.LONG,
          shadow: true,
          animation: true,
        });
      }
      
    },
    *addAddress({payload},{call,put}):any {
      console.log('新增收货地址的数据',payload.formData);
      // 处理formData数据
      const formData = new FormData();
      formData.append('user_id', payload.formData.user_id);
      formData.append('Consigner_name', payload.formData.Consigner_name);
      formData.append('consigner_phone', payload.formData.consigner_phone);
      formData.append('address_message', payload.formData.address_message);
      console.log("新增收货地址转化成formData之后的数据",formData)
      const res = yield call(axios.post,ADDADDRESS_URL,formData,{
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      console.log('新增收货地址接口返回的数据',res);
      if(res.data.code === 200 ){
        if(payload.callback && typeof payload.callback === "function") {
          payload.callback()
        }
      } else {
        Toast.show('新增收货地址失败', {
          position: Toast.positions.CENTER,
          duration: Toast.durations.LONG,
          shadow: true,
          animation: true,
        });
      }
    },
    *getCurrentUser({payload},{call,put}):any {
      console.log('user_id',payload.user_id)
      const res = yield call(axios.get,CURREBTUSER_URL,{
        params:{user_id:payload.user_id}
      });
      console.log('当前用户数据',res.data.data)
      if(res.data.code === 200 ){
        console.log("执行当前用户的code===200")
        yield put({
          type:"updateState",
          payload:{
            user:res.data.data
          }
        })
      }
      if(payload.callback && typeof payload.callback === "function") {
        payload.callback(res.data.data)
      }
    },
    *clearCurrentUser({payload},{call,put}):any {
      yield put({
        type:"updateState",
        payload:{
          user:[]
        }
      })
    },
    *deleteAddress({payload},{call,put}):any {
      console.log('删除收货地址的数据',payload.formData);
      // 处理formData数据
      const formData = new FormData();
      formData.append('user_id', payload.formData.user_id);
      formData.append('address_id', payload.formData.address_id);
      console.log("删除收货地址转化成formData之后的数据",formData)
      const res = yield call(axios.post,DELETE_URL,formData,{
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      console.log('删除收货地址接口返回的数据',res);
      if(res.data.code === 200 ){
        if(payload.callback && typeof payload.callback === "function") {
          payload.callback()
        }
      } else {
        Toast.show('删除收货地址失败', {
          position: Toast.positions.CENTER,
          duration: Toast.durations.LONG,
          shadow: true,
          animation: true,
        });
      }
    },
    *modifyAddress({payload},{call,put}):any {
      console.log('修改收货地址的数据',payload.formData);
      // 处理formData数据
      const formData = new FormData();
      formData.append('user_id', payload.formData.user_id);
      formData.append('address_id', payload.formData.address_id);
      formData.append('Consigner_name', payload.formData.Consigner_name);
      formData.append('consigner_phone', payload.formData.consigner_phone);
      formData.append('address_message', payload.formData.address_message);
      console.log("修改收货地址转化成formData之后的数据",formData)
      const res = yield call(axios.post,MODIFYADDRESS_URL,formData,{
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      console.log('修改收货地址接口返回的数据',res);
      if(res.data.code === 200 ){
        if(payload.callback && typeof payload.callback === "function") {
          payload.callback()
        }
      } else {
        Toast.show('修改收货地址失败', {
          position: Toast.positions.CENTER,
          duration: Toast.durations.LONG,
          shadow: true,
          animation: true,
        });
      }
    },
    *applyAddress({payload},{call,put}):any {
      console.log('应用收货地址的数据',payload.formData);
      // 处理formData数据
      const formData = new FormData();
      formData.append('user_id', payload.formData.user_id);
      formData.append('address_id', payload.formData.address_id);
      console.log("应用收货地址转化成formData之后的数据",formData)
      const res = yield call(axios.post,APPLYADDRESS_URL,formData,{
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      console.log('应用收货地址接口返回的数据',res);
      if(res.data.code === 200 ){
        if(payload.callback && typeof payload.callback === "function") {
          payload.callback()
        }
      } else {
        Toast.show('应用收货地址失败', {
          position: Toast.positions.CENTER,
          duration: Toast.durations.LONG,
          shadow: true,
          animation: true,
        });
      }
    },
    *compeleteInfo({payload},{call,put}):any {
      console.log('完善摄影师身份的数据', payload.formData);
      // 处理formData数据
      const formData = new FormData();
      formData.append('user_id', payload.formData.user_id);
      formData.append('experience', payload.formData.experience);
      formData.append('identity', payload.formData.identity);
      payload.formData.images.forEach((image:any) => {
        const file = {
          uri: image.uri,
          type: 'image/jpeg',
          name: image.uri.split('/').pop()
        };
        formData.append('images', file);
      });
      console.log('完善摄影师身份转化成formData之后的数据', formData);
      const res = yield call(axios.post, COMPELETEINFO_URL, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      console.log('完善摄影师接口返回的数据', res);
      if (res.data.code === 200) {
        if (payload.callback && typeof payload.callback === 'function') {
          payload.callback();
        }
      } else {
        Toast.show('完善摄影师信息失败', {
          position: Toast.positions.CENTER,
          duration: Toast.durations.LONG,
          shadow: true,
          animation: true,
        });
      }
    },
    *editUserInfo({payload},{call,put}):any {
      console.log('编辑详细信息的数据', payload.formData);
      // 处理formData数据
      const formData = new FormData();
      formData.append('user_id', payload.formData.user_id);
      formData.append('experience', payload.formData.experience);
      formData.append('username', payload.formData.username);
      formData.append('age', payload.formData.age);
      formData.append('city', payload.formData.city);
      formData.append('nature', payload.formData.nature);
      // formData.append('identity', payload.formData.identity);
      formData.append('scurpture', {
        uri: payload.formData.scurpture,
        name: 'scurpture.jpg',
        type: 'image/jpeg',
      });
      payload.formData.works && formData.append('works',JSON.stringify(payload.formData.works));
      payload.formData.newAddImages && payload.formData.newAddImages.forEach((image:any) => {
        const file = {
          uri: image.uri,
          type: 'image/jpeg',
          name: image.uri.split('/').pop()
        };
        formData.append('images', file);
      });
      console.log('编辑详细信息的formData之后的数据', formData);
      const res = yield call(axios.post, EDITUSERINFO_URL, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      console.log('编辑详细信息接口返回的数据', res);
      if (res.data.code === 200) {
        if (payload.callback && typeof payload.callback === 'function') {
          payload.callback();
        }
      } else {
        Toast.show('编辑详细信息失败', {
          position: Toast.positions.CENTER,
          duration: Toast.durations.LONG,
          shadow: true,
          animation: true,
        });
      }
    },
    *likeArticals({payload},{call,put}):any {
      console.log('收藏文章的数据',payload.formData);
      // 处理formData数据
      const formData = new FormData();
      formData.append('user_id', payload.formData.user_id);
      formData.append('artical_id', payload.formData.artical_id);
      console.log("收藏文章转化成formData之后的数据",formData)
      const res = yield call(axios.post,LIKEARTICAL_URL,formData,{
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      console.log('收藏文章接口返回的数据',res);
      if(res.data.code === 200 ){
        if(payload.callback && typeof payload.callback === "function") {
          payload.callback()
        }
      } else {
        Toast.show('收藏文章失败', {
          position: Toast.positions.CENTER,
          duration: Toast.durations.LONG,
          shadow: true,
          animation: true,
        });
      }
    },
    *cancelLikeArtical({payload},{call,put}):any {
      console.log('取消收藏文章的数据',payload.formData);
      // 处理formData数据
      const formData = new FormData();
      formData.append('user_id', payload.formData.user_id);
      formData.append('artical_id', payload.formData.artical_id);
      console.log("取消收藏文章转化成formData之后的数据",formData)
      const res = yield call(axios.post,CANCELLIKEARTICAL_URL,formData,{
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      console.log('取消收藏文章接口返回的数据',res);
      if(res && res.data.code === 200 ){
        if(payload.callback && typeof payload.callback === "function") {
          payload.callback()
        }
      } else {
        Toast.show('取消收藏文章失败', {
          position: Toast.positions.CENTER,
          duration: Toast.durations.LONG,
          shadow: true,
          animation: true,
        });
      }
    },
    *destroyAccount({payload},{call,put}):any {
      console.log('销毁账号的数据',payload.formData);
      // 处理formData数据
      const formData = new FormData();
      formData.append('user_id', payload.formData.user_id);
      console.log("销毁账号转化成formData之后的数据",formData)
      const res = yield call(axios.post,DESTROYACCOUNT_URL,formData,{
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      console.log('销毁账号接口返回的数据',res);
      if(res && res.data.code === 200 ){
        if(payload.callback && typeof payload.callback === "function") {
          payload.callback()
        }
      } else {
        Toast.show('注销账号失败', {
          position: Toast.positions.CENTER,
          duration: Toast.durations.LONG,
          shadow: true,
          animation: true,
        });
      }
    },

  },
};
export default users;
